<template>
	<el-dialog :model-value="visible" title="创建班级" width="500px" @close="handleClose"
		@update:model-value="$emit('update:visible', $event)">
		<div class="space-y-6">
			<!-- 班级名称 -->
			<div>
				<label class="block text-sm font-medium text-gray-700 mb-2">班级名称 <span
						class="text-red-500">*</span></label>
				<el-input v-model="classForm.className" placeholder="请输入班级名称" class="w-full" clearable maxlength="50"
					show-word-limit />
			</div>

			<!-- 学科 -->
			<div>
				<label class="block text-sm font-medium text-gray-700 mb-2">学科 <span
						class="text-red-500">*</span></label>
				<el-input v-model="classForm.subject" placeholder="请输入学科" class="w-full" clearable maxlength="20"
					show-word-limit />
			</div>

			<!-- 年级 -->
			<div>
				<label class="block text-sm font-medium text-gray-700 mb-2">年级 <span
						class="text-red-500">*</span></label>
				<el-input v-model="classForm.grade" placeholder="请输入年级" class="w-full" clearable maxlength="20"
					show-word-limit />
			</div>

			<!-- 学期 -->
			<div>
				<label class="block text-sm font-medium text-gray-700 mb-2">学期 <span
						class="text-red-500">*</span></label>
				<el-input v-model="classForm.semester" placeholder="请输入学期（如：2023-2024学年第一学期）" class="w-full" clearable
					maxlength="30" show-word-limit />
				<p class="text-xs text-gray-500 mt-1">例如：2023-2024学年第一学期、2024春季学期等</p>
			</div>

			<!-- 班级简介 -->
			<div>
				<label class="block text-sm font-medium text-gray-700 mb-2">班级简介</label>
				<el-input v-model="classForm.description" type="textarea" :rows="4" placeholder="请输入班级简介（可选）"
					class="w-full" maxlength="500" show-word-limit />
				<p class="text-xs text-gray-500 mt-1">简要介绍班级特点、教学目标等信息</p>
			</div>

			<!-- 班级封面图（优化按钮尺寸：与文本框同宽且更长） -->
			<div>
				<label class="block text-sm font-medium text-gray-700 mb-2">班级封面图</label>
				<el-upload class="w-full" 
					:on-change="handleFileChange"
					:before-upload="beforeImageUpload" 
					:show-file-list="true"
					:limit="1"
					action=""
					:auto-upload="false"
					list-type="picture">
					<el-button type="default" class="w-full h-20 text-base py-4">点击上传封面图</el-button>
				</el-upload>
				<p class="text-xs text-gray-500 mt-1">支持JPG、PNG格式，建议尺寸1200×600像素</p>
				<!-- 封面图预览 -->
				<div v-if="classForm.coverImageUrl" class="mt-3">
					<img :src="classForm.coverImageUrl" alt="班级封面预览" class="max-h-40 rounded border">
				</div>
			</div>

			<!-- 班级信息预览 -->
			<div class="bg-gray-50 rounded-lg p-4">
				<h4 class="font-medium text-gray-900 mb-3">班级信息预览</h4>
				<div class="grid grid-cols-2 gap-4 text-sm">
					<div>
						<span class="text-gray-600">班级名称：</span>
						<span class="text-gray-900">{{ classForm.className || '未填写' }}</span>
					</div>
					<div>
						<span class="text-gray-600">学科：</span>
						<span class="text-gray-900">{{ classForm.subject || '未填写' }}</span>
					</div>
					<div>
						<span class="text-gray-600">年级：</span>
						<span class="text-gray-900">{{ classForm.grade || '未填写' }}</span>
					</div>
					<div>
						<span class="text-gray-600">学期：</span>
						<span class="text-gray-900">{{ classForm.semester || '未填写' }}</span>
					</div>
				</div>
				<div v-if="classForm.description" class="mt-3">
					<span class="text-gray-600">班级简介：</span>
					<p class="text-gray-900 text-sm mt-1">{{ classForm.description }}</p>
				</div>
			</div>

			<!-- 错误提示 -->
			<div v-if="errorMessage" class="bg-red-50 border border-red-200 rounded-lg p-3">
				<div class="flex items-center gap-2 text-red-800">
					<el-icon>
						<Warning />
					</el-icon>
					<span class="text-sm">{{ errorMessage }}</span>
				</div>
			</div>
		</div>

		<template #footer>
			<div class="flex justify-end gap-3">
				<el-button @click="handleClose">取消</el-button>
				<el-button type="primary" @click="handleCreate" :loading="creating" :disabled="!canCreate">
					创建班级
				</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script setup>
	import {
		ref,
		reactive,
		computed
	} from 'vue'
	import { ElMessage } from 'element-plus'
	import { Warning } from '@element-plus/icons-vue'
	import { userAPI } from '@/api/user.js'

	// Props
	const props = defineProps({
		visible: {
			type: Boolean,
			default: false
		}
	})

	// Emits
	const emit = defineEmits(['update:visible', 'success'])

	// 响应式数据
	const creating = ref(false)
	const errorMessage = ref('')

	// 表单数据（所有字段均为教师自行填写）
	const classForm = reactive({
		className: '', // 班级名称（自行填写）
		subject: '', // 学科（自行填写）
		grade: '', // 年级（自行填写）
		semester: '', // 学期（自行填写）
		description: '', // 班级简介（自行填写）
		coverImageUrl: '', // 班级封面图URL
		coverImageFile: null // 班级封面图文件
	})

	// 计算属性：判断是否可以创建班级（必填项是否已填写）
	const canCreate = computed(() => {
		return classForm.className.trim() !== '' &&
			classForm.subject.trim() !== '' &&
			classForm.grade.trim() !== '' &&
			classForm.semester.trim() !== ''
	})

	// 图片上传相关方法
	const beforeImageUpload = (file) => {
		// 检查文件类型
		const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'
		if (!isJpgOrPng) {
			ElMessage.error('只能上传JPG、PNG格式的图片')
			return false
		}

		// 检查文件大小（限制5MB）
		const isLt5M = file.size / 1024 / 1024 < 5
		if (!isLt5M) {
			ElMessage.error('图片大小不能超过5MB')
			return false
		}

		return true
	}

	const handleFileChange = (file, fileList) => {
		classForm.coverImageFile = file.raw
		// 预览图片
		const reader = new FileReader()
		reader.onload = (e) => {
			classForm.coverImageUrl = e.target.result
		}
		reader.readAsDataURL(file.raw)
		ElMessage.success('封面图已选择')
	}

	// 方法：重置表单
	const resetForm = () => {
		Object.assign(classForm, {
			className: '',
			subject: '',
			grade: '',
			semester: '',
			description: '',
			coverImageUrl: '',
			coverImageFile: null
		})
		errorMessage.value = ''
	}

	// 方法：关闭弹窗
	const handleClose = () => {
		emit('update:visible', false)
		resetForm()
	}

	// 方法：创建班级
	const handleCreate = async () => {
		if (!canCreate.value) return

		try {
			creating.value = true
			errorMessage.value = ''

			// 准备提交的数据，转换为userAPI.createClass期望的格式
			const classData = {
				className: classForm.className.trim(),
				subject: classForm.subject.trim(),
				grade: classForm.grade.trim(),
				semester: classForm.semester.trim(),
				description: classForm.description.trim() || '',
				file: classForm.coverImageFile // 注意这里字段名是file而不是coverImage
			}

			// 调用真实的创建班级API
			const result = await userAPI.createClass(classData)

			ElMessage.success('班级创建成功！')
			emit('success', result.data)
			handleClose()

		} catch (error) {
			if (error.response?.data?.message) {
				errorMessage.value = error.response.data.message
			} else {
				errorMessage.value = '班级创建失败，请重试'
			}
		} finally {
			creating.value = false
		}
	}
</script>

<style scoped>
	/* 强制确保上传按钮与文本框宽度完全一致（解决Element默认样式差异） */
	:deep(.el-upload--picture) {
		width: 100% !important;
	}

	:deep(.el-button--default) {
		width: 100% !important;
		box-sizing: border-box !important;
		/* 防止内边距影响宽度 */
	}
</style>